﻿package com.schimanek.ui.scrolling 
{
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author Gregor Schimanek
	 */
	public class Scroller extends Sprite
	{
		public var scrollbar		:Sprite
		public var scrollbg		:Shape;
		private var scrollHeight	:Number;
		private var scrollContainer	:ScrollableContainer;
		public function Scroller(scrollContainer:ScrollableContainer, scrollHeight:Number) 
		{
			this.scrollContainer = scrollContainer;
			this.scrollHeight=scrollHeight
			
		}
		
		private function onBarDown(e:MouseEvent):void 
		{
			//scrollContainer.mouseChildren = false;
			scrollbar.startDrag(false, new Rectangle(0, 0, 0, scrollHeight - scrollbar.height));
			stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onDrag);
		}
		
		private function stopDragging(e:MouseEvent):void 
		{
			//scrollContainer.mouseChildren = true;
			scrollbar.stopDrag();
			stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,onDrag);

		}
		
		private function onDrag(e:MouseEvent):void 
		{
			//scrBtn._y*(textH-mc_txt._height))/(scrollBarH-1-scrollBtnH));
			scrollContainer.content.y=scrollbar.y*(scrollContainer.area.height-scrollContainer.content.height)/(scrollHeight-scrollbar.height)
		}
		
		public function checkScrollNeed():void {
			//trace(scrollContainer.content.height);
			scrollbar.y = 0;
			scrollContainer.content.y = 0;
			if (scrollContainer.content.height > scrollContainer.area.height) {
				//trace("scollneed");
				scrollbg.visible = true;
				scrollbar.visible = true;
				scrollbar.addEventListener(MouseEvent.MOUSE_DOWN, onBarDown);
			}else {
				scrollbg.visible = false;
				scrollbar.visible = false;
			}
		}
		
	}
	
}